iT邦幫忙

0

Day 16檔案與串流核心文字檔案讀取與寫入:StreamReader和StreamWriter &理解串流(Stream)

c#
  • 分享至 

  • xImage
  •  

串流(Stream)
代表一種資料的流動通道,就像水管一樣:

  • 輸入串流(Input Stream) → 從檔案讀進程式
  • 輸出串流(Output Stream) → 從程式寫出到檔案
    而StreamReader、StreamWriter就是專門用來 讀寫文字檔 (.txt) 的工具

StreamWriter(寫入檔案)
StreamWriter是用來把文字寫入檔案 的類別,屬於System.IO命名空間
它的特色是:

  • 一次可以寫一行或一段文字
  • 可以選擇是覆蓋舊檔或在原本檔案後面繼續寫
  • 搭配using可以自動關閉檔案,避免檔案被鎖住

建立 StreamWriter
https://ithelp.ithome.com.tw/upload/images/20251001/20178925AqaXEQLJ1U.png
也可以加第二個參數append來決定寫入方式:

  • false(預設值) → 覆蓋原本的檔案內容
  • true → 在檔案最後「追加」新內容
    https://ithelp.ithome.com.tw/upload/images/20251001/201789259kCwU7sTHW.png

常用方法

  • Write(string text) → 寫文字(不自動換行)
  • WriteLine(string text) → 寫文字並換行
  • Flush() → 立刻把緩衝區資料寫入檔案(通常用using不需要手動呼叫)
  • Close() → 關閉檔案(用using也會自動呼叫)

範例:覆蓋寫入
https://ithelp.ithome.com.tw/upload/images/20251001/20178925mb7Lin09lc.png

範例:追加模式(保留舊內容,繼續寫)
第一次執行 →
https://ithelp.ithome.com.tw/upload/images/20251001/20178925FkwoJTcQCJ.png
第二次執行 →
https://ithelp.ithome.com.tw/upload/images/20251001/20178925Z3bU8mwCnr.png

補充:
.txt檔會在路徑:專案資料夾\bin\Debug(自行設定檔案名稱)
也可以在程式碼中印出實際位置來確認:
Console.WriteLine("檔案位置:" + Path.GetFullPath(filePath));

StreamReader(讀取檔案)

  • 屬於 System.IO 命名空間
  • 用來從檔案(或其他文字資料來源)以串流方式讀取文字
  • 好處:可以逐行讀取(很省記憶體,適合讀大檔案)
  1. ReadLine() → 一次讀一行
    https://ithelp.ithome.com.tw/upload/images/20251001/20178925qrQbT1dNhH.png

  2. ReadToEnd() → 讀取整個檔案
    https://ithelp.ithome.com.tw/upload/images/20251001/20178925vYk3W83SO6.png

  3. Peek() → 檢查下一個字元是否存在
    https://ithelp.ithome.com.tw/upload/images/20251001/20178925SupF3y3JTy.png

範例:
https://ithelp.ithome.com.tw/upload/images/20251001/201789250T6Puns8Cm.png


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言